from django_filters import *
from django_filters.rest_framework import DjangoFilterBackend, FilterSet
from rest_framework.filters import SearchFilter, OrderingFilter

from mysqldb.models import *


class ListDjangoFilterBackend(DjangoFilterBackend):
    """自己定义list过滤器"""

    def get_schema_fields(self, view):
        if view.action not in ["list"]:
            return []
        return super().get_schema_fields(view)


class FsygShopreqsnListFilterSet(FilterSet):
    """范围过滤器"""

    wb_id = CharFilter(field_name="wb_id", help_text="场所编码")
    maid = CharFilter(field_name="maid", help_text="会员标识")
    machine_no = CharFilter(field_name="machine_no", help_text="机号")
    order_type = CharFilter(field_name="order_type", help_text="订单来源")
    order_status = CharFilter(field_name="order_status", help_text="订单状态")
    pay_type = CharFilter(field_name="pay_type", help_text="支付方式")
    message_type = CharFilter(field_name="message_type", help_text="订单类型")

    start = DateTimeFilter(
        field_name="create_time", method="filter_start", help_text="开始时间"
    )
    end = DateTimeFilter(
        field_name="create_time", method="filter_end", help_text="结束时间"
    )

    class Meta:
        model = FsygShopreqsnList
        fields = [
            "wb_id",
            "maid",
            "machine_no",
            "order_type",
            "order_status",
            "pay_type",
            "message_type",
            "start",
            "end",
        ]

    def filter_start(self, qs, name, value):
        lookup = "__".join([name, "gte"])
        return qs.filter(**{lookup: value})

    def filter_end(self, qs, name, value):
        lookup = "__".join([name, "lte"])
        return qs.filter(**{lookup: value})
